package com.ruoyi.toobit.task;

import com.ruoyi.toobit.service.TooBitApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * TooBit API定时任务
 * 用于系统定时任务管理中的任务调度
 * 
 * @author TooBit
 * @date 2025-01-06
 */
@Component("tooBitApiTask")
public class TooBitApiTask {
    
    private static final Logger log = LoggerFactory.getLogger(TooBitApiTask.class);
    
    @Autowired
    private TooBitApiService tooBitApiService;
    
    // 统计信息
    private static long totalExecutions = 0;
    private static long successExecutions = 0;
    private static long failedExecutions = 0;
    private static String lastExecutionTime = "";
    private static String lastExecutionStatus = "";
    
    /**
     * 执行TooBit API exchangeInfo获取任务 - 无参数版本
     * 调用目标字符串示例：tooBitApiTask.getExchangeInfo()
     */
    public void getExchangeInfo() {
        executeExchangeInfoTask("系统调度");
    }
    
    /**
     * 执行TooBit API exchangeInfo获取任务 - 带参数版本
     * 调用目标字符串示例：tooBitApiTask.getExchangeInfo('定时任务')
     * 
     * @param taskName 任务名称参数
     */
    public void getExchangeInfo(String taskName) {
        executeExchangeInfoTask(taskName != null ? taskName : "定时任务");
    }
    
    /**
     * 执行完整验签的exchangeInfo任务
     * 调用目标字符串示例：tooBitApiTask.getExchangeInfoWithFullSignature()
     */
    public void getExchangeInfoWithFullSignature() {
        executeFullSignatureTask("完整验签任务");
    }
    
    /**
     * 获取任务执行统计信息
     * 调用目标字符串示例：tooBitApiTask.getExecutionStatistics()
     */
    public void getExecutionStatistics() {
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        
        log.info("📊 === TooBit API任务执行统计 === [{}]", currentTime);
        log.info("   总执行次数: {} 次", totalExecutions);
        log.info("   成功次数: {} 次", successExecutions);
        log.info("   失败次数: {} 次", failedExecutions);
        log.info("   成功率: {:.2f}%", totalExecutions > 0 ? (double) successExecutions / totalExecutions * 100 : 0);
        log.info("   最后执行时间: {}", lastExecutionTime);
        log.info("   最后执行状态: {}", lastExecutionStatus);
        log.info("📊 === 统计信息输出完成 ===");
    }
    
    /**
     * 执行标准验签任务的核心逻辑
     */
    private void executeExchangeInfoTask(String taskName) {
        totalExecutions++;
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        lastExecutionTime = currentTime;
        
        log.info("⏰ === TooBit API定时任务执行 [{}] === [{}]", taskName, currentTime);
        log.info("📊 任务统计: 总执行{}次, 成功{}次, 失败{}次", totalExecutions, successExecutions, failedExecutions);
        
        try {
            // 记录开始时间
            long startTime = System.currentTimeMillis();
            
            // 执行API调用
            String response = tooBitApiService.getExchangeInfoWithSignature();
            
            long endTime = System.currentTimeMillis();
            long responseTime = endTime - startTime;
            
            if (response != null && !response.isEmpty()) {
                successExecutions++;
                lastExecutionStatus = "SUCCESS";
                
                // 分析响应数据
                int symbolCount = countOccurrences(response, "\"symbol\":");
                boolean hasServerTime = response.contains("serverTime");
                
                log.info("✅ 定时任务执行成功! [{}]", taskName);
                log.info("📊 响应时间: {}ms", responseTime);
                log.info("🏪 获取交易对数量: {} 个", symbolCount);
                log.info("🕐 服务器时间同步: {}", hasServerTime ? "正常" : "异常");
                
                // 输出关键交易对检查结果
                logKeyTradingPairs(response);
                
            } else {
                failedExecutions++;
                lastExecutionStatus = "FAILED";
                log.error("❌ 定时任务执行失败 [{}]: API响应为空", taskName);
            }
            
        } catch (Exception e) {
            failedExecutions++;
            lastExecutionStatus = "ERROR";
            log.error("🚨 定时任务执行异常 [{}]: {}", taskName, e.getMessage(), e);
        }
        
        // 输出任务执行总结
        double successRate = totalExecutions > 0 ? (double) successExecutions / totalExecutions * 100 : 0;
        log.info("📈 任务成功率: {:.2f}% ({}/{})", successRate, successExecutions, totalExecutions);
        log.info("⏰ === TooBit API定时任务完成 [{}] === [{}]", taskName, currentTime);
    }
    
    /**
     * 执行完整验签任务的核心逻辑
     */
    private void executeFullSignatureTask(String taskName) {
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        
        log.info("🔐 === TooBit API完整验签任务执行 [{}] === [{}]", taskName, currentTime);
        
        try {
            // 记录开始时间
            long startTime = System.currentTimeMillis();
            
            // 执行完整验签API调用
            String response = tooBitApiService.getExchangeInfoWithFullSignature();
            
            long endTime = System.currentTimeMillis();
            long responseTime = endTime - startTime;
            
            if (response != null && !response.isEmpty()) {
                log.info("✅ 完整验签任务执行成功! [{}]", taskName);
                log.info("📊 响应时间: {}ms", responseTime);
                log.info("🔐 HMAC SHA256签名验证: 通过");
                
                // 分析响应数据
                int symbolCount = countOccurrences(response, "\"symbol\":");
                log.info("🏪 获取交易对数量: {} 个", symbolCount);
                
            } else {
                log.error("❌ 完整验签任务执行失败 [{}]", taskName);
            }
            
        } catch (Exception e) {
            log.error("🚨 完整验签任务异常 [{}]: {}", taskName, e.getMessage(), e);
        }
        
        log.info("🔐 === TooBit API完整验签任务完成 [{}] === [{}]", taskName, currentTime);
    }
    
    /**
     * 输出关键交易对检查信息
     */
    private void logKeyTradingPairs(String response) {
        try {
            // 检查主要交易对是否存在
            String[] keyPairs = {"BTCUSDT", "ETHUSDT", "DOGEUSDT", "TRXUSDT"};
            StringBuilder pairStatus = new StringBuilder("🔍 关键交易对检查: ");
            
            for (String pair : keyPairs) {
                if (response.contains("\"" + pair + "\"")) {
                    pairStatus.append(pair).append("✅ ");
                } else {
                    pairStatus.append(pair).append("❌ ");
                }
            }
            
            log.info(pairStatus.toString());
            
        } catch (Exception e) {
            log.debug("🔍 解析交易对信息时出错: {}", e.getMessage());
        }
    }
    
    /**
     * 计算字符串中指定子串的出现次数
     */
    private int countOccurrences(String text, String pattern) {
        if (text == null || pattern == null) {
            return 0;
        }
        
        int count = 0;
        int index = 0;
        while ((index = text.indexOf(pattern, index)) != -1) {
            count++;
            index += pattern.length();
        }
        return count;
    }
}